<?php
/**
 * 后台panx商品展示列表
 * Author: lyun
 * Date: 2018/4/3
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Admin\Panx\Product;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\Panx\Product\ProductIndexRequest;
use App\Models\Admin\PanxAdmin;
use App\Models\Customer\Customer;
use App\Models\Panx\Brand;
use App\Models\Panx\Category;
use App\Models\Panx\Product;
use App\Services\Repositories\Product\ProductRepository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class ProductController extends ApiController
{
    const ROUTES = [
        'index' => 'api.admin.panx.product.index'
    ];

    /**
     * Display a listing of the resource.
     * @test
     *
     * @param ProductIndexRequest $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(ProductIndexRequest $request)
    {
        $this->checkIsTrue(PanxAdmin::checkIsSuperMan(), trans('admin.is_super_man'));

        /** @var Collection|LengthAwarePaginator $products */
        $products = Product::filterCustomerId($request->customer_id)
            ->columnsKeywordsOrLike([
                'title' => $request->keyword,
            ])
            ->filterIsSale($request->is_sale)
            ->filterIsDeleted($request->is_deleted)
            ->filterBrand($request->brand_id)
            ->filterCategory($request->category_id)
            ->with('category', 'thumbImage')
            ->orderBy($request->sort_column ?: 'created_at', $request->sort_by ?: 'DESC')
            ->paginate($request->per_page ?: 15);

        (new ProductRepository)->transformProducts($products);

        return $this->response(compact('products'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $customers = Customer::where('is_deleted', Customer::IS_NOT_DELETED)
            ->pluck('name', 'id');

        $categories = Category::where('parent_id', Category::TOP_CATEGORY)->pluck('name' , 'id');

        $brands = Brand::latest()->pluck('name', 'id');

        return $this->response(compact('customers', 'categories', 'brands'));
    }

}
